// pages/chat/chat.js

const app = getApp()

var websocket = require('../../../utils/websocket.js');

var req = require('../../../utils/token.js');
var utils = require('../../../utils/util.js');

Page({



  /**
  * 页面的初始数据
  */

  data: {
    title: {
      "flag": 1,
      "name": "你的好友"
    },
    isbottom:false, //加载时在最下面
    history:false,
    isHistorys: false,  //查看历史记录
    newslist: [],
    userInfo: [],
    uuid: '2',
    scrollTop: 0,
    increase: false,//图片添加区域隐藏
    aniStyle: true,//动画效果
    message: "",
    previewImgList: [],
    toUserInfo:[]

  },

  /**
  * 生命周期函数--监听页面加载
  */

  onLoad: function (e) {
    var that = this
    that.data.userInfo = app.globalData.userInfo;
    that.data.history = true;
    var uuid = app.globalData.userInfo.uuid.trim();
    var address = app.globalData.address.trim();
     var userId=e.userId2.trim();
    //调通接口
    //
    websocket.connect(null, '/' + uuid, '/' + userId, function (res) {
      var list = []
      var toUserInfo=[]
    var userInfo=[]
      var fig = res.data.indexOf("重复连接被挤下线了") ;
      if (fig!=-1){
        wx.showToast({
          title: '重复连接被挤下线了',
          icon: "none",
          duration: 2000
        })
      }
      
      if (that.data.history == true){
        var datas = JSON.parse(res.data)
        list = datas.list         //聊天记录
        toUserInfo = datas.user //对方user
        userInfo = app.globalData.userInfo;
        that.setData({
          toUserInfo: toUserInfo || null,
          newslist: list || null,
          userInfo: userInfo || null

        })
        that.data.history = false
      } else if (that.data.history == null){
        var datas = JSON.parse(res.data)
        that.setData({
          newslist: datas || null,
        })
        that.data.history = false
        return
      }
      else{
        var arr = JSON.parse(res.data)
        var list = that.data.newslist || null
        that.setData({
          newslist: list.concat(arr) || null
        })
      }
      if (that.data.isbottom==false){
        that.pageScrollToBottom()
        that.data.isbottom = true
      }
      
    })
  },

  // 页面卸载

  onUnload() {

    wx.closeSocket();
    wx.showToast({
      title: '连接已断开~',
      icon: "none",
      duration: 2000
    })
    var pages = getCurrentPages();
    var prevPage = pages[pages.length - 2]; //上一个页面
    //直接调用上一个页面的setData()方法，把数据存到上一个页面中去
    wx.navigateBack({//返回
      delta: 1
    })
  },

  //事件处理函数

  send: function () {

    var flag = this

    if (this.data.message.trim() == "") {

      wx.showToast({

        title: '消息不能为空哦~',

        icon: "none",

        duration: 2000

      })

    } else {

      // setTimeout(function () {

      //   flag.setData({

      //     increase: false

      //   })

      // }, 5000)
      websocket.send(
        '{ "content":"' + this.data.message + '", "date":"' + utils.formatTime(new Date()) + '", "address":"' + app.globalData.address.trim() + '", "msgId":"' + this.data.userInfo.uuid + '"}')

      this.bottom()

    }

  },

  //监听input值的改变

  bindChange(res) {

    this.setData({

      message: res.detail.value

    })

  },

  cleanInput() {

    //button会自动清空，所以不能再次清空而是应该给他设置目前的input值

    this.setData({

      message: this.data.message

    })

  },

  increase() {

    this.setData({

      increase: true,

      aniStyle: true

    })

  },

  //点击空白隐藏message下选框

  outbtn() {
    this.setData({
      increase: false,
      aniStyle: true
    })

  },

  //聊天消息始终显示最底端

  bottom: function () {

    // var query = wx.createSelectorQuery()

    // query.select('#flag').boundingClientRect()

    // query.selectViewport().scrollOffset()

    // query.exec(function (res) {

    //   wx.pageScrollTo({

    //     scrollTop: res[0].bottom // #the-id节点的下边界坐标

    //   })

    //   res[1].scrollTop // 显示区域的竖直滚动位置

    // })
    wx.createSelectorQuery().select('#flag').boundingClientRect(function (rect) {
      // 使页面滚动到底部
      wx.pageScrollTo({
        // scrollTop: rect.height,
        // duration: 1500000,
        scrollTop: 100000,
        scrollWithAnimation: true,
      })
    }).exec()
  },
  // 页面加载完成
  onReady: function () {
  
  },
  onShow:function(){
  },
  pageScrollToBottom: function () {

    wx.createSelectorQuery().select('#j_page').boundingClientRect(function (rect) {
      // 使页面滚动到底部
      wx.pageScrollTo({
        scrollWithAnimation: true,
        scrollTop: rect.bottom
      })
    }).exec()

  },
  selectHistory:function(){
    this.setData({
      isHistorys: true,
    })
    this.data.history = null;
    websocket.send("")
 
  }
})